package com.liujit.auth.security.service;

import com.liujit.auth.security.enums.PwdEncoderType;
import com.liujit.common.domain.result.Result;
import com.liujit.common.enums.ResultCode;
import com.liujit.upms.api.UpmsFeignClient;
import com.liujit.upms.domain.model.SysOauthClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

/**
 * @Description: 自定义客户端获取方式
 * @Author: liujun
 * @Date: 2021/6/27 10:31 上午
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class OauthClientService implements ClientDetailsService {

    private final UpmsFeignClient upmsFeignClient;

    @Override
    public ClientDetails loadClientByClientId(String clientId) {
        try {
            Result<SysOauthClient> result = upmsFeignClient.getByClientId(clientId);
            if (ResultCode.SUCCESS.code().equals(result.getCode())) {
                SysOauthClient client = result.getData();
                BaseClientDetails clientDetails = new BaseClientDetails(
                        client.getClientId(),
                        client.getResourceIds(),
                        client.getScope(),
                        client.getAuthorizedGrantTypes(),
                        client.getAuthorities(),
                        client.getWebServerRedirectUri());
                clientDetails.setClientSecret(PwdEncoderType.NOOP.prefix() + client.getClientSecret());
                return clientDetails;
            } else {
                log.info("客户端id不存在: {}", clientId);
                throw new NoSuchClientException("客户端id不存在: " + clientId);
            }
        } catch (EmptyResultDataAccessException e) {
            log.error("客户端id不存在: {}", clientId);
            throw new NoSuchClientException("客户端id不存在: " + clientId);
        }
    }
}
